//
//  TreeViewController.m
//  iLiteNote
//
//  Created by xiangism on 15/8/26.
//  Copyright (c) 2015年 LiteNice. All rights reserved.
//

#import "TreeViewController.h"
#import "FileData.h"
#import "GitCmd.h"
#import "TextViewController.h"
#import "WebViewController.h"
#import "RATree/RATreeView.h"
#import "LNTableViewCell.h"
#import "LNStateView.h"
#import "SettingViewController.h"
#import "CloneController.h"
#import "SlideMenuView.h"
#import "GitInfo.h"
#import "WBPopMenuModel.h"
#import "WBPopMenuView.h"
#include "NSString+NotePath.h"

@interface TreeViewController ()<RATreeViewDataSource, RATreeViewDelegate>

@property (nonatomic, strong) RATreeView *treeView;
@property (nonatomic, strong) NSMutableArray *files;
@property (nonatomic, strong) WebViewController *webView;

@end


@implementation TreeViewController

- (id)initWithWebCtrl:(WebViewController*)webVc {
    self = [super init];
    if (self) {
        self.webView = webVc;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self initWidget];
    
    [self loadData];
    [self.treeView reloadData];
}

- (void)viewDidAppear:(BOOL)animated {
}

- (void)initWidget {
    CGRect frame = [[UIScreen mainScreen]bounds];
    CGRect rectStatus = [[UIApplication sharedApplication]statusBarFrame];
    
    int w1 = 35;
    int h1 = 30;
    CGRect rectBtn1 = CGRectMake(10, rectStatus.size.height, w1, h1);
    
    UIButton *gitButton = [UIButton buttonWithType:UIButtonTypeSystem];
    gitButton.frame = rectBtn1;
    [gitButton setTitle:@"git" forState:UIControlStateNormal];
    [gitButton addTarget:self action:@selector(gitTouch:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:gitButton];
    
    UIButton *doButton = [UIButton buttonWithType:UIButtonTypeSystem];
    doButton.frame = CGRectMake(10 + w1 + 20, rectStatus.size.height, w1, h1);
    [doButton setTitle:@"do" forState:UIControlStateNormal];
    [doButton addTarget:self action:@selector(doTouch:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:doButton];
    
    int w = 70;
    int h = 30;
    CGRect rectBtn2 = CGRectMake(0, frame.size.height-h, w, h);
    UIButton *btnSetting = [UIButton buttonWithType:UIButtonTypeSystem];
    btnSetting.frame = rectBtn2;
    [btnSetting setTitle:@"Setting" forState:UIControlStateNormal];
    [btnSetting addTarget:self action:@selector(btnSettingTouch:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnSetting];
    
    UIButton *btnTest = [UIButton buttonWithType:UIButtonTypeSystem];
    btnTest.frame = CGRectMake(100, frame.size.height-h, w, h);
    [btnTest setTitle:@"Test" forState:UIControlStateNormal];
    [btnTest addTarget:self action:@selector(btnTestTouch:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnTest];
    
    CGRect treeFrame = CGRectMake(0, rectStatus.size.height+rectBtn1.size.height, 
                                  frame.size.width*2/3, 
                                  frame.size.height-rectStatus.size.height-rectBtn1.size.height-rectBtn2.size.height);
    RATreeView *treeview = [[RATreeView alloc]initWithFrame:treeFrame];
    treeview.delegate = self;
    treeview.dataSource = self;
    treeview.separatorStyle = RATreeViewCellSeparatorStyleSingleLine;
    
    [treeview registerNib:[UINib nibWithNibName:NSStringFromClass([LNTableViewCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([LNTableViewCell class])];
    [self.view addSubview:treeview];
    
    self.treeView = treeview;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark Action

- (void)showStateView:(NSInteger)r {
    NSString *message = @"git success";
    NSInteger layTime = 2;
    
    if (r == 0) {
        
    } else if (r == 12) {
        message = @"git net error, please check net";
        layTime = 3;
    } else if (r == 4) {
        message = @"conflict for push, please pull";
    } else {
        message = [NSString stringWithFormat:@"git error code %d", (int)r];
        layTime = 3;
    }
    
    LNStateView *view = [[LNStateView alloc]initWithMessage:message layTime:layTime];
    [view show];
}

- (void)btnSettingTouch:(UIButton*)btn {
    [self.slideMenu hideMenu:NO];
    
    GitInfo *info = [GitInfo shareGitInfo];
    //UINavigationController *nav = (UINavigationController*)self.webView.parentViewController;
    UINavigationController *nav = self.webView.navigationController;
    
    if (info.gitURL) {
        SettingViewController *se = [[SettingViewController alloc] init];
        se.treeViewReloadBlock = ^{
            [self loadData];
            [self.treeView reloadData];
        };
        [nav pushViewController:se animated:YES];
        
    } else {
        CloneController *vc = [[CloneController alloc] init];
        vc.treeViewReloadBlock = ^{
            [self loadData];
            [self.treeView reloadData];
        };
        
        [nav pushViewController:vc animated:YES];
    }
}

- (void)btnTestTouch:(UIButton*)btn {
    FileData *row = (FileData*)_treeView.itemForSelectedRow;
    printf("SelectNow: isFile:%d\n", row.isFile);
    
    return;
}

- (void)alertInput:(NSString*)title path:(NSString*)path handler:(void(^)(NSString *name))handler {
    [self alertInput:title path:path handler:handler text:@""];
}

- (void)alertInput:(NSString*)title path:(NSString*)path handler:(void(^)(NSString *name))handler text:(NSString*)text {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:path.lastPathComponent preferredStyle:UIAlertControllerStyleAlert];
    [alert addTextFieldWithConfigurationHandler:^(UITextField *field) {
        field.text = text;
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {}];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        if (handler) {
            UITextField *txt = alert.textFields.firstObject;
            handler(txt.text);
        }
    }];
    [alert addAction:cancelAction];
    [alert addAction:okAction];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)createNote:(NSString*)path {
    [self alertInput:@"新建笔记" path:path handler:^(NSString *name) {
        NSString *newName = [NSString stringWithFormat:@"%@/%@.txt", path, name];
        
        NSFileManager *manager = [NSFileManager defaultManager];
        [manager createFileAtPath:newName contents:nil attributes:nil];
        
        [self loadData];
        [self.treeView reloadData];
        [self.treeView expandItem:newName];
    }];
}

- (void)deleteNote:(NSString*)title path:(NSString*)path {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:path.lastPathComponent preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAct = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        
    }];
    UIAlertAction *okAct = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        NSFileManager *manager = [NSFileManager defaultManager];
        NSError *err = nil;
        [manager removeItemAtPath:path error:&err];
        
        [self loadData];
        [self.treeView reloadData];
        [self.treeView expandItem:path];
    }];
    [alert addAction:cancelAct];
    [alert addAction:okAct];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)renameItem:(NSString*)title path:(NSString*)path isFile:(BOOL)isFile {
    [self alertInput:title path:path handler:^(NSString *name) {
        NSFileManager *manager = [NSFileManager defaultManager];
        
        if (isFile) {
            NSRange range = [path rangeOfString:@"/" options:NSBackwardsSearch];
            //NSString *par = [path substringWithRange:NSMakeRange(0, range.location)];
            NSString *par = [path substringToIndex:range.location];
            NSString *newName = [NSString stringWithFormat:@"%@/%@.txt", par, name];
            
            NSLog(@"newName: %@", newName);
            [manager moveItemAtPath:path toPath:newName error:nil];
            [self loadData];
            [self.treeView reloadData];
            [self.treeView expandItem:newName];
            
        } else {
            NSRange range = [path rangeOfString:@"/" options:NSBackwardsSearch];
            NSString *par = [path substringToIndex:range.location];
            NSString *newName = [NSString stringWithFormat:@"%@/%@", par, name];
            
            NSLog(@"path: %@", newName);
            //[manager moveItemAtPath:path]
            [manager moveItemAtPath:path toPath:newName error:nil];
            [self loadData];
            [self.treeView reloadData];
            [self.treeView expandItem:newName];
        }
    } text:[path getBaseName]];
}

- (void)showMenu:(CGRect)btnRect tls:(NSArray*)titles imgs:(NSArray*)images action:(void(^)(NSInteger index))action {
    
    NSMutableArray *items = [NSMutableArray array];
    
    for (NSInteger i = 0; i < titles.count; ++i) {
        WBPopMenuModel *info = [[WBPopMenuModel alloc] init];
        info.title = titles[i];
        info.image = images[i];
        [items addObject:info];
    }
    //CGRect btnRect = btn.frame;
    CGFloat x = btnRect.origin.x-5;
    CGFloat y = btnRect.origin.y + btnRect.size.height + 10;
    
    UIWindow * window = [[[UIApplication sharedApplication] windows] firstObject];
    WBPopMenuView *view = [[WBPopMenuView alloc] initWithFrame:window.bounds];
    [view showMenu:CGRectMake(x, y, 130, 0) items:items action:^(NSInteger index) {
        action(index);
    }];
}

- (void) doNoteMenu:(CGRect)btnFrame {
    FileData *row = (FileData*)_treeView.itemForSelectedRow;
    NSArray *titles = @[@"删除", @"重命名", @"移动"];
    NSArray *images = @[@"", @"", @""];
    
    [self showMenu:btnFrame tls:titles imgs:images action:^(NSInteger index) {
        
        NSLog(@"index: %ld", index);
        NSLog(@"fileName:%@", row.path);
        
        switch (index) {
            case 0:
                [self deleteNote:@"删除笔记" path:row.path];
                break;
                
            case 1:
                [self renameItem:@"重命名笔记" path:row.path isFile:YES];
                break;
                
            case 2:
                break;
                
            default:
                break;
        }
    }];
}

- (void)doFoldMenu:(CGRect)btnFrame {
    FileData *row = (FileData*)_treeView.itemForSelectedRow;
    NSArray *titles = @[@"新建目录", @"新建笔记", @"删除", @"重命名", @"移动"];
    NSArray *images = @[@"dir", @"note", @"", @"", @""];
    
    [self showMenu:btnFrame tls:titles imgs:images action:^(NSInteger index) {
        
        switch (index) {
                //新建目录
            case 0: {
                
                break;
            }
                //新建笔记
            case 1:
                [self createNote:row.path];
                break;
                
                //删除
            case 2:
                [self deleteNote:@"删除目录" path:row.path];
                break;
                
                //重命名
            case 3:
                [self renameItem:@"重命名目录" path:row.path isFile:NO];
                break;
                
                //移动
            case 4:
                break;
            default:
                break;
        }
    }];
    
}

- (IBAction)doTouch:(UIButton*)btn {
    
    FileData *row = (FileData*)_treeView.itemForSelectedRow;
    if (row) {
        if (row.isFile) {
            [self doNoteMenu:btn.frame];
        } else {
            [self doFoldMenu:btn.frame];
        }
    }
}

- (IBAction)gitTouch:(UIButton*)btn {
    NSArray *titles = @[@"git pull", @"git push"];
    NSArray *images = @[@"pull@3x", @"push@3x"];
    NSMutableArray *items = [NSMutableArray array];
    
    for (NSInteger i = 0; i < titles.count; ++i) {
        WBPopMenuModel *info = [[WBPopMenuModel alloc]init];
        info.title = titles[i];
        info.image = images[i];
        
        [items addObject:info];
    }
    CGRect btnRect = btn.frame;
    CGFloat x = 0;
    CGFloat y = btnRect.origin.y + btnRect.size.height+10;
    
    UIWindow * window = [[[UIApplication sharedApplication] windows] firstObject];
    WBPopMenuView *view = [[WBPopMenuView alloc] initWithFrame:window.bounds];
    [view showMenu:CGRectMake(x, y, 140, 0) items:items action:^(NSInteger index) {
        if (index == 0) {
            GitInfo *info = [GitInfo shareGitInfo];
            GitControl *git= [[GitControl alloc] initWithInfo:info];
            int r = [git gitPull];
            
            if (r == 0) {
                [self loadData];
                [self.treeView reloadData];
                [self.treeView expandItem:_webView.notePath];
            }
            [self showStateView:r];
            
        } else if (index == 1) {
            GitInfo *info = [GitInfo shareGitInfo];
            GitControl *git= [[GitControl alloc] initWithInfo:info];
            int r = [git gitPush];
            
            [self showStateView:r];
        }
        
    }];
}

- (void)loadData {
    self.files = [[NSMutableArray alloc]init];
    
    GitInfo *info = [GitInfo shareGitInfo];
    if (info) {
        [self refreshFiles:self.files withPath:[info getGitPath]];
    }
}

- (void)refreshFiles:(NSMutableArray*)files withPath:(NSString*)path {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *fileList = [fileManager contentsOfDirectoryAtPath:path error:nil];
    
    for (int i = 0; i<fileList.count; ++i) {
        NSString *r = fileList[i];
        
        NSRange range = [r rangeOfString:@"." options:NSBackwardsSearch];
        if (range.length > 0) {
            NSString *ext = [r substringFromIndex:range.location];
            if ([ext compare:@".app"] == NSOrderedSame) {
                continue;
            }
        }
        
        if ([r characterAtIndex:0] == '.') {
            continue;
        }
        
        NSString *p = [NSString stringWithFormat:@"%@/%@", path, r];
        BOOL is_dir = false;
        [fileManager fileExistsAtPath:p isDirectory:&is_dir];
        
        FileData *d = [[FileData alloc]initWithName:p isFile:!is_dir children:nil];
        
        if (is_dir) {
            d.children = [[NSMutableArray alloc]init];
            [self refreshFiles:d.children withPath:p];
            [files addObject:d];
            
        } else {
            NSString *txt = [NSString stringWithFormat:@"txt"];
            if ([r.pathExtension compare:txt options:NSCaseInsensitiveSearch] == kCFCompareEqualTo) {
                [files addObject:d];
            }
        }
    }
    
    [files sortUsingComparator:^NSComparisonResult(__strong id obj1, __strong id obj2) {
        FileData *d1 = obj1;
        FileData *d2 = obj2;
       
        if (d1.isFile && !d2.isFile) {
            return NSOrderedDescending;
        } else if (!d1.isFile && d2.isFile) {
            return NSOrderedAscending;
        } else {
            return [d1.path compare:d2.path options:NSCaseInsensitiveSearch];
        }
    }];
}

#pragma mark - RATreeView Delegate

- (CGFloat)treeView:(RATreeView *)treeView heightForRowForItem:(id)item {
    return 44;
}

- (BOOL)treeView:(RATreeView *)treeView canEditRowForItem:(id)item {
    return NO;
}

- (void)treeView:(RATreeView *)treeView willExpandRowForItem:(id)item {
    FileData *fileData = item;
    LNTableViewCell *cell = (LNTableViewCell*)[treeView cellForItem:item];
    [cell setIsExpand:YES];
    
    if (!fileData.isFile) {
        LNTableViewCell *par = [treeView parentForItem:item];
        NSArray *arr;
        if (par) {
            arr = [treeView allChildren:par];
        } else {
            arr = [treeView topChildren];
        }
        for (int i = 0 ; i < arr.count; ++i) {
            id c = arr[i];
            
            if (c == item) {
                continue;
            }
            [treeView collapseRowForItem:c withRowAnimation:RATreeViewRowAnimationNone];
        }
    }
}

- (void)treeView:(RATreeView *)treeView willCollapseRowForItem:(id)item {
    LNTableViewCell *cell = (LNTableViewCell*)[treeView cellForItem:item];
    [cell setIsExpand:NO];
    
    NSArray * arr = [treeView allChildren:item];
    for (int i = 0; i < arr.count; ++i) {
        id c = arr[i];
        [treeView collapseRowForItem:c withRowAnimation:RATreeViewRowAnimationNone];
    }
    
}

- (id)treeView:(RATreeView *)treeView willSelectRowForItem:(id)item {
    return item;
}

- (void)treeView:(RATreeView *)treeView didSelectRowForItem:(id)item {
    FileData *data = item;
    if (data.isFile) {
        [self.webView navigateFile:data.path];
    }
}

#pragma mark - TreeView Data Source

- (UITableViewCell*)treeView:(RATreeView *)treeView cellForItem:(id)item {
    FileData *data = item;
    NSInteger level = [self.treeView levelForCellForItem:item];
    
    LNTableViewCell *cell = [self.treeView dequeueReusableCellWithIdentifier:NSStringFromClass([LNTableViewCell class])];
    //[cell setupWithTitle:[data getBaseName] level:level isFile:data.isFile];
    [cell setupWithTitle:[data.path getBaseName] level:level isFile:data.isFile];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (NSInteger)treeView:(RATreeView *)treeView numberOfChildrenOfItem:(id)item {
    if (item == nil) {
        return [self.files count];
    }
    FileData *data = item;
    return [data.children count];
}

- (id)treeView:(RATreeView *)treeView child:(NSInteger)index ofItem:(id)item {
    FileData *data = item;
    if (item == nil) {
        return [self.files objectAtIndex:index];
    }
    return data.children[index];
}

@end

/*- (void)listFiles {
    [self.files removeAllObjects];
    
    NSString *path = [NSString stringWithFormat:@"%@/Documents/LiteNote", NSHomeDirectory()];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error = nil;
    NSArray *fileList = [fileManager contentsOfDirectoryAtPath:path error:&error];
    
    for (int i = 0; i<fileList.count; ++i) {
        NSString *r = fileList[i];
        if ([r compare:@".git"] == NSOrderedSame) {
            continue;
        }
        NSString *p = [NSString stringWithFormat:@"%@/%@", path, r];
        BOOL is_dir = false;
        [fileManager fileExistsAtPath:p isDirectory:&is_dir];
        
        FileData *d = [FileData dataObjectWithName:p isFile:!is_dir children:nil];
        [self.files addObject:d];
    }
    
    [self.files sortUsingComparator:^NSComparisonResult(__strong id obj1, __strong id obj2) {
        FileData *d1 = (FileData*)obj1;
        FileData *d2 = (FileData*)obj2;
        if (d1.isFile && !d2.isFile) {
            return NSOrderedDescending;
        } else if (!d1.isFile && d2.isFile) {
            return NSOrderedAscending;
        } else {
            return [d1.path compare:d2.path options:NSCaseInsensitiveSearch]; //忽略大小写
        }
    }];
}*/